#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成拼音音频文件的脚本
使用 gTTS 生成中文拼音发音（一声）
需要安装: pip install gtts
"""

from gtts import gTTS
import os
import time

# 创建 sounds/pinyin 目录
pinyin_dir = 'sounds/pinyin'
os.makedirs(pinyin_dir, exist_ok=True)

# 拼音数据（添加一声拼音）
pinyin_data = {
    "initials": [
        {"text": "b", "desc": "波", "tone1": "bō"},
        {"text": "p", "desc": "坡", "tone1": "pō"},
        {"text": "m", "desc": "摸", "tone1": "mō"},
        {"text": "f", "desc": "佛", "tone1": "fō"},
        {"text": "d", "desc": "得", "tone1": "dē"},
        {"text": "t", "desc": "特", "tone1": "tē"},
        {"text": "n", "desc": "讷", "tone1": "nē"},
        {"text": "l", "desc": "勒", "tone1": "lē"},
        {"text": "g", "desc": "哥", "tone1": "gē"},
        {"text": "k", "desc": "科", "tone1": "kē"},
        {"text": "h", "desc": "喝", "tone1": "hē"},
        {"text": "j", "desc": "基", "tone1": "jī"},
        {"text": "q", "desc": "欺", "tone1": "qī"},
        {"text": "x", "desc": "希", "tone1": "xī"},
        {"text": "zh", "desc": "知", "tone1": "zhī"},
        {"text": "ch", "desc": "吃", "tone1": "chī"},
        {"text": "sh", "desc": "诗", "tone1": "shī"},
        {"text": "r", "desc": "日", "tone1": "rī"},
        {"text": "z", "desc": "资", "tone1": "zī"},
        {"text": "c", "desc": "雌", "tone1": "cī"},
        {"text": "s", "desc": "思", "tone1": "sī"},
        {"text": "y", "desc": "衣", "tone1": "yī"},
        {"text": "w", "desc": "乌", "tone1": "wū"}
    ],
    "finals": [
        {"text": "a", "desc": "啊", "tone1": "ā"},
        {"text": "o", "desc": "哦", "tone1": "ō"},
        {"text": "e", "desc": "鹅", "tone1": "ē"},
        {"text": "i", "desc": "衣", "tone1": "ī"},
        {"text": "u", "desc": "乌", "tone1": "ū"},
        {"text": "ü", "filename": "v", "desc": "迂", "tone1": "ǖ"},
        {"text": "ai", "desc": "哀", "tone1": "āi"},
        {"text": "ei", "desc": "欸", "tone1": "ēi"},
        {"text": "ui", "desc": "威", "tone1": "uī"},
        {"text": "ao", "desc": "熬", "tone1": "āo"},
        {"text": "ou", "desc": "欧", "tone1": "ōu"},
        {"text": "iu", "desc": "优", "tone1": "iū"},
        {"text": "ie", "desc": "耶", "tone1": "iē"},
        {"text": "üe", "filename": "ue", "desc": "约", "tone1": "üē"},
        {"text": "er", "desc": "儿", "tone1": "ēr"},
        {"text": "an", "desc": "安", "tone1": "ān"},
        {"text": "en", "desc": "恩", "tone1": "ēn"},
        {"text": "in", "desc": "因", "tone1": "īn"},
        {"text": "un", "desc": "温", "tone1": "ūn"},
        {"text": "ün", "filename": "vn", "desc": "晕", "tone1": "ǖn"},
        {"text": "ang", "desc": "昂", "tone1": "āng"},
        {"text": "eng", "desc": "亨", "tone1": "ēng"},
        {"text": "ing", "desc": "英", "tone1": "īng"},
        {"text": "ong", "desc": "轰", "tone1": "ōng"}
    ],
    "wholes": [
        {"text": "zhi", "desc": "知", "tone1": "zhī"},
        {"text": "chi", "desc": "吃", "tone1": "chī"},
        {"text": "shi", "desc": "诗", "tone1": "shī"},
        {"text": "ri", "desc": "日", "tone1": "rī"},
        {"text": "zi", "desc": "资", "tone1": "zī"},
        {"text": "ci", "desc": "雌", "tone1": "cī"},
        {"text": "si", "desc": "思", "tone1": "sī"},
        {"text": "yi", "desc": "衣", "tone1": "yī"},
        {"text": "wu", "desc": "乌", "tone1": "wū"},
        {"text": "yu", "desc": "迂", "tone1": "yū"},
        {"text": "ye", "desc": "耶", "tone1": "yē"},
        {"text": "yue", "desc": "约", "tone1": "yuē"},
        {"text": "yuan", "desc": "渊", "tone1": "yuān"},
        {"text": "yin", "desc": "因", "tone1": "yīn"},
        {"text": "yun", "desc": "晕", "tone1": "yūn"},
        {"text": "ying", "desc": "英", "tone1": "yīng"}
    ]
}

def generate_audio(tone1_text, filename, pinyin_text=""):
    """生成单个拼音音频
    使用带一声声调符号的拼音来生成音频（如 bā, mā）
    """
    try:
        # 使用带一声声调符号的拼音生成音频
        # 这样 gTTS 会读出拼音的一声，而不是汉字的实际声调
        tts = gTTS(text=tone1_text, lang='zh', slow=False)
        filepath = os.path.join(pinyin_dir, filename)
        tts.save(filepath)
        print(f"✓ 生成: {filename} ({pinyin_text} -> {tone1_text})")
        return True
    except Exception as e:
        print(f"✗ 失败: {filename} ({pinyin_text} -> {tone1_text}) - {e}")
        return False

print("=" * 60)
print("拼音音频生成工具")
print("=" * 60)
print("\n开始生成拼音音频文件...\n")

total_count = 0
success_count = 0

# 生成声母音频
print("生成声母音频...")
for pinyin in pinyin_data["initials"]:
    total_count += 1
    filename = f"{pinyin['text']}.mp3"
    # 使用带一声声调符号的拼音（如 bō, pō）来生成音频
    tone1 = pinyin.get('tone1', pinyin['text'])
    if generate_audio(tone1, filename, pinyin['text']):
        success_count += 1
    time.sleep(0.5)  # 避免请求过快

print("\n生成韵母音频...")
for pinyin in pinyin_data["finals"]:
    total_count += 1
    # 处理特殊字符 ü
    filename = pinyin.get('filename', pinyin['text']) + ".mp3"
    # 使用带一声声调符号的拼音（如 ā, ō）来生成音频
    tone1 = pinyin.get('tone1', pinyin['text'])
    if generate_audio(tone1, filename, pinyin['text']):
        success_count += 1
    time.sleep(0.5)

print("\n生成整体认读音频...")
for pinyin in pinyin_data["wholes"]:
    total_count += 1
    filename = f"{pinyin['text']}.mp3"
    # 使用带一声声调符号的拼音（如 zhī, chī）来生成音频
    tone1 = pinyin.get('tone1', pinyin['text'])
    if generate_audio(tone1, filename, pinyin['text']):
        success_count += 1
    time.sleep(0.5)

print("\n" + "=" * 60)
print(f"完成！成功: {success_count}/{total_count}")
print(f"音频文件保存在: {pinyin_dir}/")
print("=" * 60)
